package com.blb.ishop.util;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 日志通知类
 */
@Aspect
@Component
public class LogAdvise {

    //创建日志输出对象
    private Logger logger = Logger.getLogger(LogAdvise.class);

    //定义切点
    @Pointcut("execution(* com.blb.ishop.service.*ServiceImpl.*(..)) && @annotation(com.blb.ishop.util.MyLog)")
    public void pointcut(){
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //输出当类和方法名，形参的值，执行开始时间，执行耗时，返回值
        logger.debug("类名："+joinPoint.getTarget().getClass() +",方法名：" + joinPoint.getSignature().getName());
        logger.debug("执行时间：" + LocalDateTime.now());
        logger.debug("参数：");
        for(Object arg : joinPoint.getArgs()){
            logger.debug("类型：" + arg.getClass() +",值：" + arg);
        }
        long start = System.currentTimeMillis();
        //执行原有方法
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        logger.debug("执行耗时：" + (end - start));
        logger.debug("返回值：" + proceed);
        logger.debug("-----------------------------------------------");
        // 获取方法上的注解
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = joinPoint.getTarget().getClass().getMethod(methodSignature.getName(),methodSignature.getParameterTypes());
        MyLog annotation = method.getAnnotation(MyLog.class);
        if(annotation != null){
            System.out.println(annotation.value());
        }
        return proceed;
    }

    //Throwable --> Exception Error
    @AfterThrowing(value = "pointcut()",throwing = "throwable")
    public void afterThrowing(Throwable throwable){
        logger.error("出现异常！",throwable);
    }

    //    @Before("pointcut()")
//    public void beforeLog(){
//        System.out.println("这是前置通知");
//    }
//
//    @After("pointcut()")
//    public void afterLog(){
//        System.out.println("这是后置通知");
//    }
//
//    @AfterReturning("pointcut()")
//    public void afterReturning(){
//        System.out.println("这是最终通知");
//    }

}
